package org.dei.perla.sys.device.plugnplay.plugnplaymanager;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.tools.JavaCompiler;
import javax.tools.JavaFileObject;
import javax.tools.StandardJavaFileManager;
import javax.tools.ToolProvider;
import javax.tools.JavaCompiler.CompilationTask;

import org.dei.perla.sys.device.plugnplay.xsdgeneratedclasses.PerlaDevice;


public class Compiler {
	// compila f. f DEVE essere una directory contenente
	// uno o piu file .java
	// options sono le opzioni che
	// e' possibile dare al compilatore quando viene invocato con javac
	public boolean compileFiles(File f, String[] options) {
		JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
		StandardJavaFileManager fileManager = compiler.getStandardFileManager(
				null, null, null);
		// opzioni di default (metti i .class in bin)
		if (options == null || options.length == 0)
			options = new String[] { "-d", "bin" };
		// prepare the source file(s) to compile
		List<File> sourceFileList = new ArrayList<File>();
		for (File file : f.listFiles())
			if (file.getName().contains(".java"))
				sourceFileList.add(file);
		if (sourceFileList.isEmpty())
			return false;
		Iterable<? extends JavaFileObject> compilationUnits = fileManager
				.getJavaFileObjectsFromFiles(sourceFileList);
		CompilationTask task = compiler.getTask(null, fileManager, null, Arrays
				.asList(options), null, compilationUnits);
		boolean result = task.call();
		try {
			fileManager.close();
		} catch (IOException e) {
			e.printStackTrace();
			System.err.println("Error closing source files");
		}
		if (result) {
			System.out.println("Compilation was successful");
			return true;
		} else
			System.out.println("Compilation failed");
		return false;
	}

	public Compiler() {
		super();
	}

	public static void main(String args[]) {
		ClassTreeManager ctm = new ClassTreeManager();
		Compiler c = new Compiler();
		try {
			ctm.createJavaFiles("org.dei.perla.sys.device.plugnplay.xsdgeneratedclasses", "testDSPic.xml", null);
		} catch (Exception e) {
			e.printStackTrace();
			return;
		}
		File dir = new File(ctm.getParameterManager().getFileDir()
				+ctm.getParameterManager().getPerlaDevice().getName());
		c.compileFiles(dir, null);
	}

}